import re
import time, datetime
from neomodel import Q, db
from network.models import Industry, Institute, Major, Classes, Student, HasRel

# For easily access each of the model classes programmatically, create a key-value map.
MODEL_ENTITIES = {
    'Industry': Industry,
    'Institute': Institute,
    'Major': Major,
    'Classes': Classes,
    'HAS': HasRel,
    'Student': Student
}


def str_2_datetime(datestr='2021-10-12'):
    """

    :param datestr: 2021-10-12
    :return:
    """
    fmt = '%Y-%m-%d'
    time_tuple = time.strptime(datestr, fmt)
    year, month, day = time_tuple[:3]
    a_date = datetime.date(year, month, day)
    return a_date


def get_classes_students(classes_name):
    """
    返回包含名字为 classes_name 的班级的全部学生
    :param classes_name:
    :return:
        student_node_set 学生节点的集合， 还未序列化 不能hash
    """
    # 获取符合的行业
    student_set = set()
    classes_nodes = Classes.nodes
    classes_nodes.filter(name__icontains=classes_name)
    # 每个行业筛选出本行业的学生
    for industrys_node in classes_nodes:
        # 对学生求并集
        pass
    return student_set

def get_industrys_students(industrys_name):
    """
    返回包含名字为 industrys_name 的行业的全部学生
    :param industrys_name:
    :return:
        student_node_set 学生节点的集合， 还未序列化 不能hash
    """
    result, meta = db.cypher_query(f"match (i:Industry)-[:HAS]-(s:Student)  where i.name =~ '.*{industrys_name}.*' return i, s")
    for row in result:
        industry_node = row[0]
        student_node = row[1]



def filter_student(industrys, major, classes, name, nation, attendance_date, limit):
    """
    筛选学生
    :param industrys: 行业名称
    :param major: 专业名称
    :param classes: 班级名称
    :param name: 姓名
    :param nation: 民族
    :param attendance_date:  入学年份 字符串 2021
    :return:
    """
    # 先按照名字查
    students_nodes = Student.nodes
    if name:
        students_nodes.filter(name__icontains = name)
    # 按照民族查
    if nation:
        students_nodes.filter(nation__icontains = nation)
    # 按照入学年份
    if attendance_date:
        # 转为date对象
        attendance_date = str_2_datetime(attendance_date)
        students_nodes.filter(attendance_date = attendance_date)
        # 筛选
    # 按照班级

    # 按照专业

    # 按照行业
    return [students_node.serialize for students_node in students_nodes]


def path_to_graph(rows):
    nodes_set = set()
    rel_set = set()
    nodes_list = []
    rels_list = []
    for row in rows:
        path = row[0]
        for node in path.nodes:
            nodes_set.add(node)
        for rel in path.relationships:
            rel_set.add(rel)
    for node in nodes_set:
        type_name = re.match(r"frozenset\({'(.*)'}\)", str(node.labels)).group(1)
        nodes_list.append(MODEL_ENTITIES[type_name].inflate(node).serialize)
    for rel in rel_set:
        type_name = rel.type
        rels_list.append(MODEL_ENTITIES[type_name].inflate(rel).serialize)
    return {
        'node' : nodes_list,
        'edge': rels_list
    }

if __name__ == '__main__':
    str_2_datetime()
